<template>
  <div class="group-page">
    <!-- left-group-box start -->
    <div class="left-group-box" :class="{ 'unlock-tag-active': !isTagLocked }">
      <div class="top">
        <div>
          <el-checkbox
            v-model="allChecked"
            @change="changeAllCheck"
            :disabled="isTagLocked"
            :indeterminate="isIndeterminate"
            >全选</el-checkbox
          >
          <i
            @click="changeTagLocked"
            :class="[isTagLocked ? 'icon-locked' : 'icon-lock']"
          ></i>
        </div>
        <i class="icon-add" title="新增视点组" @click="openPanel('add')"></i>
        <i class="icon-delete1" title="删除"  @click="deleteGroups"></i>
      </div>
      <div class="btm ag-scrollbar">
        <el-collapse v-model="activeNames" @change="handleChange">
          <el-collapse-item title="全局视点" name="全局视点">
            <p
              v-for="(item, index) in globalList"
              :key="item.imageStoreDirId"
              :class="{ active: curGroupIndex === item.imageStoreDirId }"
              @click="onChangeGroup(item.imageStoreDirId, item.imageStoreDirName, index)"
            >
              <el-tooltip v-if="item.imageStoreDirName.length>9" :content="item.imageStoreDirName" placement="bottom-start" effect="dark">
                <span class="ellips">{{ item.imageStoreDirName }}</span>
              </el-tooltip>
              <span v-else class="ellips">{{ item.imageStoreDirName }}</span>
            </p>
          </el-collapse-item>
          <el-collapse-item title="自建视点" name="自建视点">
            <p
              v-for="(item, index) in otherList"
              :key="item.imageStoreDirId"
              :class="{ active: curGroupIndex === item.imageStoreDirId }"
              @click="onChangeGroup(item.imageStoreDirId, item.imageStoreDirName, index)"
              :draggable="!isTagLocked"
              @dragstart="dragstart(item)"
              @dragenter="dragenter(item, $event)"
              @dragend="dragend(item, $event)"
            >
              <el-checkbox
                v-model="item.checked"
                @change="changeCheck"
              ></el-checkbox
              >
              <el-tooltip v-if="item.imageStoreDirName.length>9" :content="item.imageStoreDirName" placement="bottom-start" effect="dark">
                <span class="ellips">{{ item.imageStoreDirName }}</span>
              </el-tooltip>
              <span v-else class="ellips">{{ item.imageStoreDirName }}</span>
              <span v-show="isTagLocked">
                <i class="icon-edit" @click="openPanel('edit',item)"></i>
                <i class="icon-delete" @click="showDeleteConfirm(item.imageStoreDirId)"></i>
              </span>
            </p>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <AddOrEditViewPointGroup
      :visible="visible_addGroup"
      :viewPointGroupPopup="viewPointGroupPopup"
      :nowGroupId="isGroupId"
      :nowGroupName="isGroupName"
      :parentId="parentId"
      @addGroup="addNewGroup"
      @updateList="$emit('updateList')"
      @getGroupList="getGroupList"
      @close="visible_addGroup = false"
    ></AddOrEditViewPointGroup>
  </div>
</template>
<script>
import imageDataApi from "@/views/js/api/imageDataApi";
import dirImageDataApi from "@/views/js/api/dirImageDataApi.js";
import AddOrEditViewPointGroup from "./addOrEditViewPointGroup.vue";
export default {
  components: {
    AddOrEditViewPointGroup,
  },
  props: {
    viewList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  computed: {
  },
  watch: {
    //当前选中的分组的id
    nowGroupId(nv) {
      this.isCanEdit = this.otherList.some((item) => {
        return item.imageStoreDirId == nv;
      });
      this.$emit("isCanEdit", this.isCanEdit);
      this.$emit("selectGroupId", nv);
    },
  },
  data() {
    return {
      // 是否成功获取list信息
      getListFlag: false,
      //分类是否锁上
      isTagLocked: true,
      //当前分类
      curGroupIndex: 0,
      //当前选中的组id
      nowGroupId: undefined,
      //当前选中的组name
      nowGroupName: undefined,
      //打开弹框的类型 add/edit
      viewPointGroupPopup: "add",
      //弹框是否可见
      visible_addGroup: false,
      //分组列表
      groupList: [],
      //全局视点分组列表
      globalList: [],
      //自建视点分组列表
      otherList: [],
      //全选
      allChecked: false,
      //半选中
      isIndeterminate: false,
      //当前选中的数组
      checkedList: [],
      //
      activeNames: ["自建视点"],
      //分组是否可编辑
      isCanEdit: false,
      //自建分组父id
      parentId:'',
      isGroupName:'', //新增、编辑的组名称
      isGroupId:'',//新增、编辑的组id
    };
  },
  mounted() {
    this.getGroupList();
  },
  methods: {
    handleChange(val) {},
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 获取分组数据
     * @param {*}
     * @return {*}
     */    
    getGroupList() {
      let _this = this;
      let params = { code: "AgCIM-viewPoints" };
      dirImageDataApi.treeByCode(params).then((res) => {
        if (res.success) {
          _this.getListFlag = true;
          _this.arrayToTree(res.content);
          _this.changeCheck();
        }
      });
    },
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 数据处理
     * @param {*} arr 原始数组
     * @return {*}
     */    
    arrayToTree(arr) {
      let _this = this;
      let root = [];
      const obj = {};
      //数据转换map类型 key=id
      arr.forEach((item) => {
        item.children = [];
        obj[item.imageStoreDirId] = item;
      });
      //数据转化为树型结构
      arr.forEach((item) => {
        if (obj[item.imageStoreDirParentId]) {
          obj[item.imageStoreDirParentId].children.push(item);
        } else {
          root.push(item);
        }
      });
      console.log(root)
      _this.groupList = root[0].children;
      _this.groupList.map((item) => {
        if (item.imageStoreDirCode == "global-AgCIM-viewPoints") {
          _this.globalList = item.children;
          // _this.globalList = _.cloneDeep(item.children); //全局分组
        } else if (item.imageStoreDirCode == "other-AgCIM-viewPoints") {
          _this.parentId = item.imageStoreDirId;
          _this.otherList = item.children;
          // _this.otherList = _.cloneDeep(item.children); //自建分组
          // item.children.forEach((child,index)=>{
          //   _this.$set(_this.otherList, index, child);
          // })
          _this.$emit("getOtherGroup", _this.otherList);
        }
      });
    },
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 分组单条删除
     * @param {*}
     * @return {*}
     */   
    showDeleteConfirm(id) {
      let _this = this;
      this.$confirm("你确定要删除该分组吗？", "分组删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = id;
          dirImageDataApi.deleteCascadeList(params).then((res) => {
            if (res.success) {
              _this.$message({
                message: "删除分组成功!",
                type: "success",
              });
              _this.getGroupList();
              _this.allChecked = false;
              _this.isIndeterminate = false;
              setTimeout(function (){
                if (_this.getListFlag){
                  _this.changeRightList();
                }else{
                  _this.setTimeChangeRightList();
                }
              }, 1000);
            } else {
              _this.$message({
                message: "删除失败!原因：" + res.message,
                type: "warning",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 删除多个组，对应的多个列表
     * @param {*}
     * @return {*}
     */    
    async deleteGroups() {
      let _this = this;
      let vm = this;
      let arr = this.checkedList;
      if (arr.length == 0) {
        return this.$message.info("请先选择分组");
      }
      this.$confirm(
        "你确定要删除选中的视点组以及视点组下所有的视点吗？",
        "视点组删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          type: "warning",
          center: true,
        }
      )
        .then(async () => {
          //删除多个分组
          let result = [];
          _this.checkedList.forEach((item) => {
            result.push(item.imageStoreDirId);
          });
          let params = result.join(",");
          dirImageDataApi.deleteCascadeList(params).then((res) => {
            if (res.success) {
              _this.$message({
                message: "删除成功!",
                type: "success",
              });
              vm.allChecked = false;
              vm.isIndeterminate = false;
              vm.getListFlag = false;
              vm.getGroupList();
              setTimeout(function (){
                if (vm.getListFlag){
                  vm.changeRightList();
                }else{
                  vm.setTimeChangeRightList();
                }
              }, 1000);
            } else {
              _this.$message({
                message: "删除失败!原因：" + res.message,
                type: "warning",
              });
            }
          });
        })
        .catch(() => {
          _this.$message.success("取消");
        });
    },
    setTimeChangeRightList(){
      let vm = this;
      setTimeout(function (){
        if (vm.getListFlag){
          vm.changeRightList();
        }
      }, 1000);
    },
    changeRightList(){
      let vm = this;
        if(vm.otherList[0]){
          vm.onChangeGroup(vm.otherList[0].imageStoreDirId, vm.otherList[0].imageStoreDirName, 0);
        }else{
          vm.onChangeGroup(null);
        }
    },
    //打开弹框
    openPanel(type,item) {
      this.visible_addGroup = true;
      this.viewPointGroupPopup = type;
      if(type=='add'){
        this.isGroupName = '';
      }
      else{
        this.isGroupName = item.imageStoreDirName;
        this.isGroupId = item.imageStoreDirId;
      }
    },
   /**
     * @lastUpdateBy : 韩怡婷
     * @description: 添加分组
     * @param {*} val
     * @return {*}
     */    
    addNewGroup(val) {
      let _this = this;
      let params = {
        imageStoreDirName: val,
        imageStoreDirParentId: this.parentId,
      };
      dirImageDataApi.addDirImage(params).then((res) => {
        if (res.success) {
          this.$message({
            message: "添加分组成功!",
            type: "success",
          });
          _this.getGroupList();
        }
      });
    },
    //全选
    changeAllCheck(val) {
      for (let i = 0; i < this.otherList.length; i++) {
        this.otherList[i].checked = this.allChecked;
      }
      if (val) {
        this.isIndeterminate = false;
        this.checkedList = this.otherList;
      } else {
        this.checkedList = [];
      }
    },
    changeCheck(data) {
      this.checkedList = this.otherList.filter((item) => {
        return item.checked;
      });
      let len = this.checkedList.length;
      if (0 < len && len < this.otherList.length) {
        this.allChecked = false;
        this.isIndeterminate = true;
      } else {
        if (len == this.otherList.length && this.otherList.length != 0) {
          this.allChecked = true;
        }
        this.isIndeterminate = false;
      }
    },
    onChangeGroup(val, name, index) {
      this.$emit("resetRightListAllChecked");
      this.nowGroupId = val;
      this.nowGroupName = name;
      this.curGroupIndex = val;
    },
    changeTagLocked() {
      this.isTagLocked = !this.isTagLocked;
      this.isIndeterminate = false;
      this.allChecked = false;
      if(this.isTagLocked){
        this.otherList.forEach((item) => {
          item.checked = false;
        })
      }
    },
    dragstart(value) {
      if (this.isTagLocked) return;
      this.oldData = value;
    },
    dragenter(value) {
      if (this.isTagLocked) return;
      this.newData = value;
    },
    // 拖拽最终操作
    dragend(value) {
      if (this.isTagLocked) return;
      if (this.oldData !== this.newData) {
        let oldIndex = this.otherList.indexOf(this.oldData);
        let newIndex = this.otherList.indexOf(this.newData);
        let newItems = [...this.otherList];
        // 删除旧的节点
        newItems.splice(oldIndex, 1);
        // 在列表中目标位置增加新的节点
        newItems.splice(newIndex, 0, this.oldData);
        this.otherList = [...newItems];
        this.onChangeGroup(this.oldData.id, this.oldData.name, newIndex);
        this.dragSort(this.otherList);
      }
    },
    /**
     * @lastUpdateBy : 韩怡婷
     * @description: 拖拽排序
     * @param {*} list 列表
     * @return {*}
     */    
    dragSort(list) {
      let params = [];
      list.map((item) => {
        params.push(item.imageStoreDirId);
      });
      dirImageDataApi.dirDragSort(params).then((res) => {
      });
    },
  },
};
</script>
<style src="../css/style.css"></style>
<style lang="less" scoped>
.left-group-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 200px;
  height: 100%;
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;

    .el-checkbox {
      margin-right: 8px;
    }
  }

  .btm {
    min-height: 300px;
    display: block;
    border-right: 1px solid rgba(255, 255, 255, 0.53);
    height: calc(100% - 94px);
    .drag-move {
      transition: transform 0.5s;
    }
    p {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 40px;
      cursor: pointer;
      padding: 0 14px;
      position: relative;
      i {
        display: none;
        margin-left: 6px;
      }

      .el-checkbox {
        display: none;
        margin-right: 3px;
      }

      &:hover {
        background: rgba(255, 255, 255, 0.35);
        .ellips{
          width: 124px;
        }
        i {
          display: inline-block;
        }
      }

      &.active {
        background: #1e90ff;
        color: #fff;
      }

      .ellips {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
        width: 160px;
        display: inline-block;
        vertical-align: top;
        padding-left: 40px;
      }
    }
  }

  .icon-delete1 {
    display: none;
  }

  &.unlock-tag-active {
    .btm .el-checkbox {
      display: inline-block;
      position: absolute;
    }

    .icon-delete1 {
      display: inline-block;
    }

    .icon-add {
      display: none;
    }
  }
}

.classify-box {
  width: 400px;
  left: 50%;
  top: 30%;
}

::v-deep .is-disabled .el-checkbox__inner,
::v-deep .el-checkbox__inner {
  background: transparent;
}
.title {
  margin: 0 !important;
  height: 40px;
}
.el-collapse {
  border: none;
}
.el-collapse ::v-deep.el-collapse-item__header {
  background-color: rgba(30, 144, 255, 0.3);
  color: #fff;
  border-bottom: none;
  font-size: 14px;
  padding: 0 70px 0 38px;
  height: 40px;
}

.el-collapse ::v-deep.el-collapse-item__wrap {
  background-color: rgba(255, 255, 255, 0);
  border-bottom: none;
}
.el-collapse ::v-deep.el-collapse-item__content {
  color: rgba(255, 255, 255, 0.7);
  padding-bottom: 0;
}
.el-collapse ::v-deep.el-collapse-item__arrow{
  margin-left: -74px;
}
.el-collapse ::v-deep.el-icon-arrow-right:before {
  content: "\e791";
}
</style>